/* vcc/plugins/script/script.c 
 * 
 * This file is part of vcc. 
 * 
 * vcc is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * vcc is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with vcc. If not, see <https://www.gnu.org/licenses/>
 */ 




#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <vcc/vcc.h>
#include <vcc/pretty.h>
#include <vcc/plugin.h>
#include <vcc/version.h>
#include <vcc/interfaces.h>

int do_cmd_if(int argc, char **argv);

struct cmdtable script_cmdtab[] = {
	{ "-if", do_cmd_if, "-if condition then ... else ..." }, 

	{ NULL, NULL, NULL }
};

struct plugin plg_script = {
	.state = 0, 
	.name = "script", 
	.descr = "Standard vcc script. ", 
	.cmdtab = script_cmdtab
};

#define this_plg (&plg_script)

static char *copy_until(char **argv, char *until, int *dst) {
	int i;
	char buf[MSG_SIZE];

	memset(buf, 0, MSG_SIZE);

	for (i = *dst; argv[i] && strcmp(argv[i], until); i++) {
		strcat(buf, argv[i]);
		strcat(buf, " ");
	}

	if (!argv[i]) {
		if (i == *dst) 
			return NULL;
		
		else 
			return strdup(buf);
	}

	*dst = ++i;
	return strdup(buf);
}


static int parse_if(char **argv, char **cond, char **then, char **else_then) {
	int i = 1;

	*cond = copy_until(argv, "then", &i);
	*then = copy_until(argv, "else", &i);

	/* it must present */
	*else_then = copy_until(argv, "", &i);

	if (!*cond || !*then || !*else_then) 
		return 1;

	return 0;
}


int do_cmd_if(int argc, char **argv) {
	char *cond, *then, *else_then;

	plg_check_enabled();

	if (argc < 4) {
		fprintf(stderr, _("usage: -if condition then ... else ...\n"));

		return 1;
	}

	if (parse_if(argv, &cond, &then, &else_then)) 
		return 1;

	/* we always use '0' for success ... */
	if (!handle_command(cond)) 
		handle_command(then);

	else {
		if (!else_then) 
			return 0;

		handle_command(else_then);
	}
	
	free(cond);
	free(then);
	free(else_then);

	return 0;
}


